#!/usr/bin/env python
# -*- coding:utf-8 -*-


import mechanize
from bs4 import BeautifulSoup
from mylog import MyLog
import codecs
from get_headers import get_headers


class KugouItem(object):
    username = None


class LoadKugou(object):
    def __init__(self):
        # self.url = 'http://www.kugou.com/'
        self.url = 'http://www.kugou.com/newuc/user/uc/'
        self.log = MyLog()
        self.request_head_file = 'request_head.py'

        self.spider(self.url)


    def get_response_content(self, url):
        self.log.info('Begin To Create Machenize Browser')
        br = mechanize.Browser()
        br.set_handle_equiv(True)
        br.set_handle_redirect(True)
        br.set_handle_referer(True)
        br.set_handle_robots(True)
        br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),
        max_time=1)
        headers = get_headers(self.request_head_file)
        br.addheaders = headers
        br.open(url)
        return br.response().read()


    def spider(self, url):
        response_content = self.get_response_content(url)

        print response_content

        soup = BeautifulSoup(response_content, 'lxml')
        username = soup.find('a', attrs={'class': 'kg_uc_avatar_name',
        'id': 'myucname'}).get_text()

        items = []

        item = KugouItem()
        item.username = username
        self.log.info('Get A Item')
        self.log.info(username)

        items.append(item)

        self.pipelines(items)


    def pipelines(self, items):
        filename = 'kugou.txt'
        with codecs.open(filename, 'w', encoding='utf8') as fp:
            for item in items:
                fp.write(item.username)

        self.log.info('Write To File %s Success' % filename)


if __name__ == '__main__':
    LK = LoadKugou()
